<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import { onMounted, ref } from 'vue'
import { baseURL } from '@/utils/request'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/stores'
import { io, type Socket } from 'socket.io-client'
import { onUnmounted } from 'vue'
import type { Message, TimeMessages } from '@/types/room'
import { MsgType, OrderType } from '@/enums'
import type { ConsultOrderItem } from '@/types/consult'
import { getConsultOrderDetail } from '@/services/consult'
import { nextTick } from 'vue'
import { showToast } from 'vant'
import { stringifyQuery } from 'vue-router'

const useStore = useUserStore()
const route = useRoute()
let socket: Socket
const list = ref<Message[]>([])
// 安装 pnpm add sokect.io-client 包
onMounted(() => {
  // 在组件挂载完毕，进行socket连接
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${useStore.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })
  // 监听连接成功
  socket.on('connect', () => {
    list.value = []
    console.log('connect')
  })
  // 监听关闭连接
  socket.on('disconnect', () => {
    console.log('disconnect')
  })
  // 监听错误消息
  socket.on('connect_error', () => {
    console.log('connect_error')
  })
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    // console.log(data)
    const arr: Message[] = []
    data.forEach((item, index) => {
      if (index === 0) lastTime.value = item.createTime
      arr.push({
        id: item.createTime,
        msgType: MsgType.Notify,
        createTime: item.createTime,
        msg: { content: item.createTime }
      })
      arr.push(...item.items)
    })
    list.value.unshift(...arr)
    loading.value = false
    if (data.length === 0) return showToast('没有历史数据了')
    if (initMsg.value) {
      nextTick(() => {
        window.scrollTo(0, document.body.scrollHeight)
        initMsg.value = false
      })
    }
  })
  socket.on('statusChange', () => {
    console.log('状态变化了')
    loadConsult()
  })
  socket.on('receiveChatMsg', async (val) => {
    console.log(val)
    list.value.push(val)
    // 第一种写法
    // await nextTick()
    // window.scrollTo(0, document.body.scrollHeight);
    // 第二种写法
    nextTick(() => {
      window.scrollTo(0, document.body.scrollHeight)
    })
  })
})
onUnmounted(() => {
  // 组件卸载关闭连接
  socket.close()
})
defineOptions({
  name: 'Room'
})
const consult = ref<ConsultOrderItem>()
const loadConsult = async () => {
  const { data } = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = data
}
onMounted(() => {
  loadConsult()
})
const handleSendText = (val: string) => {
  console.log('儿子给的数据', val)
  socket.emit('sendChatMsg', {
    from: useStore.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: {
      content: val
    }
  })
}
const initMsg = ref(true)
const loading = ref(false)
const lastTime = ref('')
const onRefresh = () => {
  // setTimeout(() => {
  //   showToast('刷新成功')
  //   loading.value = false
  // }, 1000)
  socket.emit('getChatMsgList', 20, lastTime.value, consult.value?.id)
}
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="问诊室" />
    <room-status
      :status="consult?.status"
      :countdown="consult?.countdown"
    ></room-status>
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message :list="list"></room-message>
    </van-pull-refresh>
    <room-action
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="handleSendText"
    ></room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
